package com.example.mtblog.security;

import cn.hutool.core.util.StrUtil;

import com.example.mtblog.common.Result;
import com.example.mtblog.tool.SecurityUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver;

import java.io.IOException;
import java.io.Serial;
import java.io.Serializable;

/**
 * 认证失败处理类
 */
@Component
public class FailureCrossing implements AuthenticationEntryPoint, Serializable {
    @Serial
    private static final long serialVersionUID = 1L;

    // 接口不合法会走到这个方法里面
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException {

        String message = StrUtil.format("没有权限访问:{}", request.getRequestURI());  // 错误信息
        SecurityUtils.renderJson(response, Result.noAuth(message));
    }

}
